package com.swap.quartz.job.jobs;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.swap.business.domain.SwapDeviceInfo;
import com.swap.business.service.DeviceInfoService;
import com.swap.common.exception.BusinessException;
import com.swap.common.utils.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author JerryLu
 * @date 2024/10/15 14:54
 * @description 定时清理过期信息
 */
public class SwapRemoveHandlerJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(SwapRemoveHandlerJob.class);

    private final RabbitTemplate rabbitTemplate;
    private final DeviceInfoService infoService;

    public SwapRemoveHandlerJob(RabbitTemplate rabbitTemplate, DeviceInfoService infoService) {
        this.rabbitTemplate = rabbitTemplate;
        this.infoService = infoService;
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            log.info("定时清理过期数据开始，执行时间:{}", DateUtils.getTime());
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 减去一个月
            LocalDateTime oneMonthAgo = now.minusMonths(1);

            QueryWrapper<SwapDeviceInfo> query = Wrappers.query();
            query.gt("collect_time", oneMonthAgo);
            List<SwapDeviceInfo> list = infoService.list(query);
            for (SwapDeviceInfo div : list) {
                String content = JSON.toJSONString(div);
                rabbitTemplate.convertAndSend("swap_exchange", "swap.remove", content, message -> {
                    message.getMessageProperties().setContentEncoding("UTF-8");
                    return message;
                });
            }
        } catch (BusinessException e) {
            log.error("初始job执行失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("初始job执行失败：" + e.getMessage(), e);
        }
    }
}
